const express = require('express')
const sqlHelper = require('../utils/sqlHelper')
const router = express.Router()

// 请求所有车辆数据
router.get('/get-all-data', (req, res) => {
  sqlHelper(`select * from car`, (error, result) => {
    if (error) {
      console.log(error);
      res.send({
        code: 500,
        data: null,
        msg: '查询失败'
      })
    } else {

      const mapResult = result.map(item => {
        if (item.cost) {
          item.status = true
          item.tag = '已完成'
          return item
        } else {
          item.status = false
          item.tag = '未完成'
          return item
        }
      })
      res.send({
        code: 200,
        data: mapResult,
        msg: '查询成功'
      })
    }
  })
})

// 添加车辆数据接口
router.post('/add-car', (req, res) => {
  const { car_number, car_type, in_time, ismonthly, unit } = req.body
  sqlHelper(`insert into car (car_number,car_type,in_time,ismonthly,unit) values ('${car_number}','${car_type}','${in_time}','${ismonthly}','${unit}')`, (error, result) => {
    if (error) {
      console.log(error);
      res.send({ code: 500, data: null, msg: '数据添加失败' })
    } else {
      res.send({ code: 200, data: null, msg: '数据添加成功' })
    }
  })
})

// 更新车辆数据接口
router.post('/update', (req, res) => {
  const { id, out_time, diff_time, cost } = req.body
  sqlHelper(`update car set out_time='${out_time}',diff_time='${diff_time}',cost='${cost}' where id=${id}`, (error, result) => {
    if (error) {
      console.log(error);
      res.send({ code: 500, data: null, mag: '更新数据失败' })
    } else {
      res.send({ code: 200, data: null, mag: '更新数据成功' })
    }
  })
})





module.exports = router